<template>
  <div style="background-color: white; min-height: 100vh;">
    <van-form @submit="submitForm">
      <searchable-picker
        v-model="form.moneyType"
        :columns="dict.type.crm_money_type"
        valueKey="value"
        labelKey="label"
        label="款项类型"
        placeholder="请选择款项类型"
        :rules="[{ required: true, message: '请选择款项类型不能为空' }]"
        :readonly="this.collectPayMoneyId !== '-1'"
      />

      <searchable-picker
        v-model="form.orderId"
        :columns="projectList"
        valueKey="orderId"
        labelKey="orderName"
        label="所属项目"
        placeholder="请选择所属项目"
        @change="getOrderRegisterInfo"
        :rules="[{ required: true, message: '所属项目不能为空' }]"
      />

      <searchable-picker
        v-model="form.userId"
        :columns="userList"
        valueKey="userId"
        labelKey="userName"
        label="款项归属人"
        placeholder="请选择款项归属人"
        :rules="[{ required: true, message: '款项归属人不能为空' }]"
      />

      <div class="details" v-if="form.moneyType === '1'">
        <div class="details-header">收款详情</div>
        <van-collapse
          v-model="collecActiveNames"
          class="product"
          v-for="(collecDetails, index) in form.collectDetailsList"
          :key="index"
        >
          <van-collapse-item
            :title="'详情' + (index + 1)"
            :name="index + 1"
            icon="ellipsis"
            class="details-body"
          >
            <div class="details-button">
              <el-button
                type="text"
                @click="addExpenses(form.collectDetailsList, '0')"
                v-if="index === form.collectDetailsList.length - 1"
                >新增</el-button
              >
              <el-button
                type="text"
                style="color: red"
                @click="delExpenses(form.collectDetailsList, index)"
                v-if="form.collectDetailsList.length > 1"
                :disabled="collecDetails.flag"
                >删除</el-button
              >
            </div>
            <searchable-picker
              v-model="collecDetails.collectDetailsName"
              :columns="dict.type.crm_money_status"
              valueKey="value"
              labelKey="label"
              label="收款名称"
              placeholder="点击选择收款名称"
              :rules="[{ required: true, message: '收款名称不能为空' }]"
            />
            <van-field
              v-model="collecDetails.collectDetailsTime"
              label="预计收款时间"
              placeholder="请选择预计收款时间"
              @click="collecDetails.collectDetailsTimeFlag = true"
              :rules="[{ required: true, message: '预计收款时间不能为空' }]"
            />
            <van-calendar
              v-model="collecDetails.collectDetailsTimeFlag"
              @confirm="
                onConfirm(
                  $event,
                  collecDetails,
                  'collectDetailsTimeFlag',
                  'collectDetailsTime'
                )
              "
              :min-date="minDate"
              :max-date="maxDate"
            />
            <van-field
              v-model="collecDetails.collectDetailsAmount"
              label="预计收款金额(元)"
              placeholder="请输入预计收款金额(元)"
              type="number"
            />
            <searchable-picker
              v-model="collecDetails.collectDetailsStatus"
              :columns="dict.type.crm_collect_money_status"
              valueKey="value"
              labelKey="label"
              label="收款状态"
              placeholder="点击选择收款状态"
              :rules="[{ required: true, message: '收款状态不能为空' }]"
            />
            <van-field
              v-model="collecDetails.remark"
              label="备注"
              placeholder="请输入备注"
            />
          </van-collapse-item>
        </van-collapse>
        <div style="height: 10px; background-color: #eceff2"></div>
      </div>

      <div class="details" v-else>
        <div class="details-header">付款列表详情</div>
        <van-collapse
          v-model="payActiveNames"
          class="product"
          v-for="(payDetails, index) in form.payDetailsList"
          :key="index"
        >
          <van-collapse-item
            :title="'详情' + (index + 1)"
            :name="index + 1"
            icon="ellipsis"
            class="details-body"
          >
            <div class="details-button">
              <el-button
                type="text"
                @click="addExpenses(form.payDetailsList, '1')"
                v-if="index === form.payDetailsList.length - 1"
                >新增</el-button
              >
              <el-button
                type="text"
                style="color: red"
                @click="delExpenses(form.payDetailsList, index)"
                v-if="form.payDetailsList.length > 1"
                >删除</el-button
              >
            </div>
            <searchable-picker
              v-model="payDetails.detailsType"
              :columns="dict.type.crm_fee_type"
              valueKey="value"
              labelKey="label"
              label="费用类型"
              placeholder="点击选择费用类型"
              :rules="[{ required: true, message: '费用类型不能为空' }]"
            />
            <van-field
              v-model="payDetails.detailsName"
              label="付款名称"
              placeholder="请输入付款名称"
              :readonly="payDetails.flag"
              :rules="[{ required: true, message: '请输入付款名称' }]"
            />
            <van-field
              v-model="payDetails.payDetailsTime"
              label="付款时间"
              placeholder="请选择付款时间"
              @click="payDetails.payDetailsTimeFlag = true"
            />
            <van-calendar
              v-model="payDetails.payDetailsTimeFlag"
              @confirm="
                onConfirm($event, payDetails, 'payDetailsTimeFlag', 'payDetailsTime')
              "
              :min-date="minDate"
              :max-date="maxDate"
            />
            <van-field
              v-model="payDetails.detailsAmount"
              label="付款金额(元)"
              placeholder="请输入付款金额(元)"
              type="number"
            />
            <searchable-picker
              v-model="payDetails.payDetailsStatus"
              :columns="dict.type.crm_pay_money_status"
              valueKey="value"
              labelKey="label"
              label="付款状态"
              placeholder="点击选择付款状态"
              :rules="[{ required: true, message: '付款状态不能为空' }]"
            />
            <van-field
              v-model="payDetails.remark"
              label="备注"
              placeholder="请输入备注"
            />
          </van-collapse-item>
        </van-collapse>
        <div style="height: 10px; background-color: #eceff2"></div>
      </div>

      <van-field
        v-model="form.remark"
        label="备注"
        placeholder="请输入内容"
        type="textarea"
        autosize
        :row="3"
        style="margin-bottom: 50px"
      />
      <div class="mobile-footer">
        <van-button
          native-type="submit"
          style="width: 49%; border-radius: 10px"
          @click="auditStatus = '0'"
          >暂存</van-button
        >
        <van-button
          type="info"
          native-type="submit"
          style="width: 49%; border-radius: 10px"
          @click="auditStatus = '1'"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import {
  getCollectPayMoney,
  addCollectPayMoney,
  updateCollectPayMoney,
} from "@/api/crm/collectPayMoney";


import { getOrderRegisterInfo } from "@/api/crm/orderRegister";

import { getUserListByStatus } from "@/api/system/user";

import { getCrmProjectAllNoPage } from "@/api/crm/project";
export default {
  name: "CollectPayMoney",
  dicts: [
    "crm_money_type",
    "crm_money_status",
    "crm_collect_money_status",
    "crm_pay_money_status",
    "sys_audit_status",
    "crm_fee_type",
  ],
  data() {
    return {
      minDate: new Date(2010, 0, 1),
      maxDate: new Date(2030, 0, 31),
      auditStatus: "",
      collecActiveNames: [],
      payActiveNames: [],
      form: {
        moneyType: "1",
        collectDetailsList: [
          {
            collectDetailsName: null,
            collectDetailsTime: new Date(),
            collectDetailsAmount: 0,
            collectDetailsStatus: "0",
            remark: "",
          },
        ],
        payDetailsList: [
          {
            detailsName: null,
            payDetailsTime: new Date(),
            detailsAmount: 0,
            payDetailsStatus: "0",
            remark: "",
          },
        ],
      },
      userList: [],
      projectList: [],
      collectPayMoneyId: "",
      // 控制change事件什么时候执行
      chanegFlag: true
    };
  },
  watch: {
    "form.collectDetailsList": {
      handler(newList, oldList) {
        this.buildActiveNames(
          this.form.collectDetailsList,
          "collecActiveNames"
        );
      },
      deep: true,
    },
    "form.payDetailsList": {
      handler(newList, oldList) {
        this.buildActiveNames(this.form.payDetailsList, "payActiveNames");
      },
      deep: true,
    },
  },
  async created() {
    this.collectPayMoneyId = this.$route.params.collectPayMoneyId;
    this.reset();
    await this.getUserListByStatus();
    await this.getCrmProjectAllNoPage();
    if (this.collectPayMoneyId !== "-1") {
      await this.handleUpdate();
    } else {
      this.chanegFlag = false
    }
  },
  mounted() {},
  methods: {
    buildActiveNames(arr, field) {
      this[field] = [];
      for (let i = 1; i <= arr.length; i++) {
        this[field].push(i);
      }
    },
    getCrmProjectAllNoPage() {
      getCrmProjectAllNoPage({}).then((res) => {
        this.projectList = res.data;
      });
    },
    handleUpdate() {
      getCollectPayMoney(this.collectPayMoneyId).then((response) => {
        this.form = response.data;
      });
    },
    onConfirm(date, details, flag, fildes) {
      details[flag] = false
      details[fildes] = `${date.getFullYear()}-${
        date.getMonth() + 1
      }-${date.getDate()}`;
      this.$forceUpdate()
    },
    isNumber(value) {
        return /^[+-]?\d+(\.\d+)?$/.test(value);
    },
    /** 表单悬着项目id 获取项目立项费用 */
    getOrderRegisterInfo(value) { 
      if(this.chanegFlag) {
        this.chanegFlag = false
        return
      }
      getOrderRegisterInfo({ orderId: value }).then((res) => {
        this.form.payDetailsList = res.data.detailsList;
        this.form.payDetailsList = this.form.payDetailsList
          .filter((item) =>  this.isNumber(item.detailsAmount))
          .map((item) => ({
            ...item,
            payDetailsTimeFlag: false,
            flag: true          
          }));
      });
    },
    async getUserListByStatus() {
      await getUserListByStatus({ status: "0" }).then((res) => {
        this.userList = res.data;
      });
    },
    cancel() {
      this.reset();
      this.$emit("cancel");
    },
    addExpenses(detailList, flag) {
      let obj = {}

      if(flag === '0') {
          obj = {
              collectDetailsName: null,
              collectDetailsTime: this.parseTime(new Date(), "{y}-{m}-{d}"),
              collectDetailsAmount: 0,
              collectDetailsStatus: "0",
              collectDetailsTimeFlag: false
          }
      } else {
          obj = {
              detailsName: null,
              payDetailsTime: this.parseTime(new Date(), "{y}-{m}-{d}"),
              detailsAmount: 0,
              payDetailsStatus: "0",
              remark: "",
              payDetailsTimeFlag: false
          }
      }

      detailList.push(obj);
    },
    delExpenses(detailList, index) {
      detailList.splice(index, 1);
    },
    reset() {
      this.form = {
        collectPayMoneyId: null,
        moneyType: "1",
        userId: null,
        orderId: null,
        projectId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        auditStatus: null,
        instanceId: null,
        nodeCode: null,
        nodeName: null,
        flowStatus: null,
        delFlag: null,
        collectDetailsList: [
          {
            collectDetailsName: null,
            collectDetailsTime: this.parseTime(new Date(), "{y}-{m}-{d}"),
            collectDetailsAmount: 0,
            collectDetailsStatus: "0",
            collectDetailsTimeFlag: false
          },
        ],
        payDetailsList: [
          {
            detailsName: null,
            payDetailsTime: this.parseTime(new Date(), "{y}-{m}-{d}"),
            detailsAmount: 0,
            payDetailsStatus: "0",
            remark: "",
            payDetailsTimeFlag: false
          },
        ],
      };
    },
    /** 提交按钮 */
    submitForm() {
      this.form.auditStatus = this.auditStatus
      if (this.form.collectPayMoneyId != null) {
        updateCollectPayMoney(this.form).then((response) => {
          this.$toast.success("修改成功");
          this.$router.replace("/crm/collectPayMoney");
        });
      } else {
        addCollectPayMoney(this.form).then((response) => {
          this.$toast.success("新增成功");
          this.$router.replace("/crm/collectPayMoney");
        });
      }
    },
  },
};
</script>

<style scoped  lang="scss">
.submitButton {
  width: 95%;
  height: 50px;
  position: fixed;
  top: 90%;
  left: 10px;
}

::v-deep .van-collapse-item__content {
  padding: 0;
}

::v-deep .product .van-collapse-item__title {
  background-color: #eceff2;
  padding: 5px 16px;
}

.details {
  border-bottom: 1px solid #eceff2;

  .details-header {
    padding: 10px 16px 3px;
    color: #323233;
    font-size: 14px;
    line-height: 24px;
    background-color: #fff;
  }

  .details-footer {
    text-align: center;
    .el-button--text {
      font-size: 18px;
    }
  }

  .details-body {
    position: relative;
  }

  .details-button {
    position: absolute;
    z-index: 1;
    right: 10px;
    top: 35px;
  }
}
</style>